from pynput import keyboard
import queue
import time
import threading
import asyncio, asyncvnc


async def VNCconsumer():
    holdingKeyArray = [] # 一个数组，记录了当前按下的所有按键
    async with asyncvnc.connect('localhost') as client:
        while True:
            # 等待获取新按键（这个get方法会阻塞线程）
            newKey = keyQueue.get(True)
            print('comsume {} time{}'.format(newKey, time.ctime(time.time())))

            with client.keyboard.hold(newKey):
                await asyncio.sleep(1)

class KeyBean:
    def __init__(self, key: str, holdOrRelease: str):
        self.key = key
        self.holdOrRelease = holdOrRelease

# keyboard的消费者线程
class ConsumerThread(threading.Thread):
    def __init__(self, name, queue):
        super().__init__()
        self.name = name
        self.queue = queue

    def run(self):
        print('Thread: {} start at {}'.format(self.name, time.ctime(time.time())))

        # 启动VNC协程（这个协程内部会阻塞线程。这个写法很屎，但我不熟悉协程，python多线程，keyboard库，asyncVNC这些代码，所以暂时想不出更好的）
        asyncio.run(VNCconsumer())

def on_press(key):
    try:
        print('alphanumeric key {0} pressed'.format(key.char))
        # 将按下的按键塞进队列中
        keyQueue.put(key.char)
    except AttributeError:
        print('special key {0} pressed'.format(key))

def on_release(key):
    print('{0} released'.format(key))
    if key == keyboard.Key.esc:
        # Stop listener
        return False


keyQueue = queue.Queue()

threads = []
[threads.append(ConsumerThread(str(i), keyQueue)) for i in range(1,2)]

# 启动所有线程
[t.start() for t in threads]


# Collect events until released
with keyboard.Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()